package com.wsjj.yjh;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

//1.批处理
public class WordCountBatchDemo {
    public static void main(String[] args) throws Exception {
//        1.创建环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
//        2.读取文件
        DataSource<String> stringDataSource = env.readTextFile("input/flink.txt");
//        3.进行切割
//        FlatMapOperator<String, Tuple2<String, Long>> stringTuple2FlatMapOperator = stringDataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
//            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
//                String[] split = value.split(" ");
//                for (int i = 0; i < split.length; i++) {
//                    out.collect(new Tuple2<String, Long>(split[i], 1L));
//                }
//            }
//        });
        FlatMapOperator<String, Tuple2<String, Long>> stringTuple2FlatMapOperator = stringDataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                String[] s = value.split(" ");
                for (String s1 : s) {
                    out.collect(Tuple2.of(s1, 1L));

                }
            }
        });

//        4.聚合
        UnsortedGrouping<Tuple2<String, Long>> tuple2UnsortedGrouping = stringTuple2FlatMapOperator.groupBy(0);
        AggregateOperator<Tuple2<String, Long>> sum = tuple2UnsortedGrouping.sum(1);

//        5.输出
        sum.print();

    }
}
